﻿/*

Created by  : Dipin Kumar Krishnan
Description : This js contains the jQuery version on the predictive search. This files used in Site Themes.


*/

var psS_TimeOut_PSChangeLoc; //This is for time out
var changeLocation_PredictiveSelectedId; // which one is selected
var mySearchAjax;
var mySearchAjaxPmap = new Array();
var browser = "";
var _mCityId = 0;

/* The on keyup function which triggers the predictive search */

function fnPredictiveSearchLoadProductName(event, txtbox, OnEnterPressedFunction, flag) {

    var city = txtbox.value;
    var cityid = 0;
    if (city.length >= 1) { /* Condition invokes the search if more than 1 character is entered in the textbox */

        var cityid = 0;
        txtbox.setAttribute('cityid', cityid);
        SearchPredictiveChangeLocation(event, txtbox, OnEnterPressedFunction, flag);

    }
    else if (city.length == 0) { /* This condition is to load the default set of themes when the textbox does not have any content */
        DeletePredictiveSearch_ChangeLocation();
        //bindTemplatesOnPredictiveSearch($(txtbox).val());
    }
    if (city.length >= 2) {
        if ($('#divChangeLocationPredictiveSearch') != null) {
            var pRow = $('.HdrPop_PerdictiveRow_Prod');
            var pRowSelected = $('.HdrPop_PerdictiveRow_Prod_hover');
            if (pRow.length > 0 || pRowSelected.length > 0) {
                $('#divChangeLocationPredictiveSearch').css('display', '');
            }

        }
    }
    else {
        if ($('#divChangeLocationPredictiveSearch') != null)
            $('#divChangeLocationPredictiveSearch').css('display', 'none');
    }
    var cityid = 0;
}
function include_css(css_file, func) {
    var html_doc = document.getElementsByTagName('head')[0];

    var count = 0;
    var link_doc = document.getElementsByTagName('link');

    for (var i = 0; i < link_doc.length; i++) {
        if (link_doc[i].href == css_file) {
            count++;
        }
    }

    if (count == 0) {
        css = document.createElement('link');
        css.setAttribute('rel', 'stylesheet');
        css.setAttribute('type', 'text/css');
        css.setAttribute('href', css_file);
        html_doc.appendChild(css);

        css.onreadystatechange = function () {
            if (css.readyState == 'complete') {
                if (func != null) {
                    func();
                }
            }
        }
        css.onload = function () {
            if (func != null) {
                func();
            }
        }
    }
    return false;
}
function getHostPath() {
    if (location.href.indexOf('localhost') > -1) {
        return "localhost:3000";
    }
    else {
        return "statictest.inthemo.com";
    }
}

/* Function to delete the active predictive dropdown */
function DeletePredictiveSearch_ChangeLocation() {
    if ($('#divChangeLocationPredictiveSearch') != null) {
        $('#divChangeLocationPredictiveSearch').remove();
        $('#txtPredictiveSearch').val = '';
        changeLocation_PredictiveSelectedId = null;
    }
}

function closeChangeLocationPopUp() {
    if ($('#divChangeLocationPredictiveSearch')) {
        $('#divChangeLocationPredictiveSearch').remove();
    }
    if ($('#changeLocationPopUp') != null) {
        $('#changeLocationPopUp').remove();
        $('#LocHeader').remove();
    }

    MOChangeLocation = null;
}
var xhr = null;

/* Function to load the predictive dropdown. */
var serviceUrl = '';
function LoadAndDisplaySearchPredictiveCities_ChangeLocation(txtSearch, txtBoxId, OnEnterPressedFunction, flag) {
    if (xhr != null) {
        xhr.abort();
    }
    if (location.href.indexOf('complaints') > -1) {
        serviceUrl = "/_services/predictiveSearchProductLoadAll.ashx";
    }
    else {
        serviceUrl = "/_services/loadPredictiveProduct.ashx";
    }
    xhr = $.ajax({
        type: 'get',
        url: serviceUrl,
        datatype: 'html',
        data: '&keyword=' + txtSearch + '&cateId=' + $('select[id*=ddlProdCate] option:selected').val(),
        error: function (request, error) { //alert(error); 
        },
        success: function (transport) {

            /* Function binds themes on the grid container or list view container */
            //bindTemplatesOnPredictiveSearch(txtSearch);

            DeletePredictiveSearch_ChangeLocation();

            if (transport.length > 0) {
                $('#clickAddProduct').hide();
                var divChangeLocationPredictiveSearch = $("<div id='divChangeLocationPredictiveSearch' class='HdrPop_Perdictive' style='width: 285px;z-Index:100000;position:absolute;overflow-y:auto;overflow-x:hidden;height:auto;max-height:336px;' onclick: 'javascript:xStopPropagation(event);' />");
                $('.container').append(divChangeLocationPredictiveSearch);

                for (var i = 0; i < transport.length; i++) {
                    var item = transport[i];
                    var searchPredictiveRowDiv;
                    if (flag == 'true') {
                        searchPredictiveRowDiv = $("<div id='pLocationRow_" + item.themeid + " 'themeid='" + item.themeid + "' themename='" + item.prodName + "' name='pLocationRow' class='HdrPop_PerdictiveRow_Prod' ItemNum=" + i + " />");
                        $(searchPredictiveRowDiv).click(function () { ChangeLocationPSMouseClick(OnEnterPressedFunction) });
                    }
                    else {
                        searchPredictiveRowDiv = $("<div id='pLocationRow_" + item.themeid + "' themeid='" + item.themeid + "' name='pLocationRow'  themename='" + item.prodName + "' class='HdrPop_PerdictiveRow_Prod' ItemNum=" + i + " />");
                        $(searchPredictiveRowDiv).click(function () { ChangeLocationPSMouseClick(OnEnterPressedFunction) });
                    }
                    $(searchPredictiveRowDiv).mouseover(function () { ChangeLocationPSMouseEvent(this, 'pLocationRow_' + item.themeid, true) });
                    $(searchPredictiveRowDiv).mouseout(function () { ChangeLocationPSMouseEvent(this, 'pLocationRow_' + item.themeid, false) });
                    var predictiveCityDiv = $("<div id='predictiveCityDivID' class='HdrPop_Perdictive_city' style= 'width:320px' />");
                    var divThemeName = $("<span id='thmName_" + item.themeid + "' name='" + item.prodName + "' class='HdrPop_Perdictive_cityName' />");
                    $(divThemeName).text(item.prodName);
                    $(predictiveCityDiv).append(divThemeName);
                    $(searchPredictiveRowDiv).append(predictiveCityDiv);
                    $(divChangeLocationPredictiveSearch).append(searchPredictiveRowDiv);
                }

                $('#divContainerPredictive').append(divChangeLocationPredictiveSearch);

                $('body').click(function () { DeletePredictiveSearch_ChangeLocation(); });

                var divPosition = 100;

                if ($('#divChangeLocationPredictiveSearch') != null) {

                    $('#divChangeLocationPredictiveSearch').css('left', divPosition[0] - 3 + 'px');
                    $('#divChangeLocationPredictiveSearch').css('top', divPosition[1] + 22) + 'px';
                    $('#divChangeLocationPredictiveSearch').css('display', '');

                    $('window').unbind(function () {
                        var divPosition = $('txtBoxId').position();
                        if ($('#divChangeLocationPredictiveSearch') != null) {

                            $('#divChangeLocationPredictiveSearch').css('left', divPosition[0] - 3 + 'px');
                            $('#divChangeLocationPredictiveSearch').css('top', divPosition[1] + 22) + 'px';
                            $('#divChangeLocationPredictiveSearch').css('display', '');
                        }
                    });

                    //$('window').scroll(evt_ChangeLocationMove(this, txtBoxId));
                }
            }
            else {
                $('#clickAddProduct').show();
                //                var divChangeLocationPredictiveSearch = $("<div id='divChangeLocationPredictiveSearch' class='HdrPop_Perdictive' style='width: 285px;z-Index:100000;position:absolute;overflow-y:auto;overflow-x:hidden;height:auto;max-height:336px;' onclick: 'javascript:xStopPropagation(event);' />");
                //                $('.container').append(divChangeLocationPredictiveSearch);
                //                var predictiveCityDiv = $("<div id='predictiveCityDivID' class='HdrPop_Perdictive_city' style= 'width:320px' />");
                //                var divThemeName = $("<span class='HdrPop_Perdictive_cityName' />");
                //                $(divThemeName).text("No Products added");
                //                $(predictiveCityDiv).append(divThemeName);
                //                $(searchPredictiveRowDiv).append(predictiveCityDiv);
                //                $(divChangeLocationPredictiveSearch).append(searchPredictiveRowDiv);

                //                $('#divContainerPredictive').append(divChangeLocationPredictiveSearch);

                //                $('body').click(function () { DeletePredictiveSearch_ChangeLocation(); });
            }

        }
    });
}
function evt_ChangeLocationMove(e) {

    var eSource = Event.element(e);
    var args = $A(arguments);

    var txtBoxId = args[1];

    var divPosition = FindObjectPosition($(txtBoxId));
    if ($('#divChangeLocationPredictiveSearch') != null) {
        if (txtBoxId != 'txtChangeCity' && txtBoxId != 'input_HeaderCityPredictiveSearch' && txtBoxId != 'txtUserHomeCity') {
            $('#divChangeLocationPredictiveSearch').style.left = (divPosition[0] - 5) + "px";
            $('#divChangeLocationPredictiveSearch').style.top = (divPosition[1] + 22) + "px";
        }
    }
    else {
        Event.stopObserving(txtBoxId, 'scroll', evt_ChangeLocationMove);
    }
}

//The function which changes the text in the textbox from the dropdown either by click or enter key
function MainSearch_LocationRefresh(thmID, thmName) {
    _mCityId = thmID;
    if (navigator.appName == "Microsoft Internet Explorer") {
        var txtbox = document.getElementById('txtProductName');
        txtbox.value = thmName;
    }
    else {
        $('#txtProductName').attr('cityid', thmID);
        $('#txtProductName').val(thmName);
    }
}
//...............................................................................................

function DeleteHeaderPredictiveSearchDivs() {
    DeleteHeaderPredictiveResults();
    closeChangeLocationPopUp();
    if ($('predectiveSearchFrame')) {
        $('predectiveSearchFrame').css('display', 'none');
        $('#txtPredictiveSearch').val = '';
    }
}
function onFocusSelect(txtBoxId) {
    if ($F(txtBoxId) != "Search for location") {
        $(txtBoxId).focus();
        $(txtBoxId).select();
    }
}
function DeleteHeaderPredictiveResults() {
    if ($('#divHeaderPredictiveSearchResults')) {
        //Effect.Fade('ul_HeaderSearchMainContent', {duration:.50});
        $('#divHeaderPredictiveSearchResults').remove();
        if ($('#liHeaderSearchTipText')) {
            $('#liHeaderSearchTipText').className = 'HH_Tip';
            $('#liHeaderSearchTipText').childNodes[0].className = 'HH_Tip_span';
            $('#spanHeaderSearchText').className = "HH_Tip_span";
            $('#spanHeaderSearchText').innerHTML = 'Start typing to get suggestions';
        }
    }
}
function closeChangeLocationPopUp() {
    if ($('#divChangeLocationPredictiveSearch')) {
        $('#divChangeLocationPredictiveSearch').remove();
    }
    if ($('#changeLocationPopUp') != null) {
        $('#changeLocationPopUp').remove();
        $('#LocHeader').remove();
    }

    MOChangeLocation = null;
}
function xStopPropagation(e) {


    if ((navigator.userAgent.indexOf("MSIE") > -1 && (navigator.userAgent.indexOf("MSIE 5") == -1 || navigator.userAgent.indexOf("MSIE 6") == -1) && !(navigator.userAgent.indexOf("opera") > -1))) { //IE


        if (!e) e = window.event; e.cancelBubble = true;
    }
    else {
        e.stopPropagation();
    }
}
function resetCityValues() {
    if ($('ctl00_ContentPlaceHolder1_preRegCityId')) {
        $('ctl00_ContentPlaceHolder1_preRegCityId').value = '';
    }
}
function getSitePath() {

    return window.location.host;


}
function submitButton(e, but) {
    var characterCode;
    if (!e)
        e = window.event;
    if (e && e.which) {
        e = e;
        characterCode = e.which;
    }
    else {
        e = event;
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {

        if (browser == 'IE') {
            if (but != null) {
                try {
                    but.onclick();
                } catch (e) { if (e.name == "TypeError") eval(but.onclick); }
            }
        }
        else {
            if (but != null) {
                if (but.value == undefined) {

                    //but.onclick();
                    $(but).click();
                }
                else {

                    but.click();
                }
            }

        }


        return false;
    }
    else {
        return true;
    }
}
var Clicked = false;
var CountryName = '';
function ChangeLocationPSMouseClick(OnEnterPressedFunction) {
    if (changeLocation_PredictiveSelectedId != null && jQuery.isFunction(OnEnterPressedFunction)) {
        var pId = changeLocation_PredictiveSelectedId.split('_')[1];

        var themeID = pId;
        var themeName = $('.HdrPop_PerdictiveRow_Prod_hover').attr('themename');
        OnEnterPressedFunction(themeID, themeName);
        //bindTemplatesOnPredictiveSearch(themeName);
        DeletePredictiveSearch_ChangeLocation();
    }
}
function CompatibleMouseOver() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return "mouseenter";
    else
        return "mouseover";
}

function CompatibleMouseOut() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return "mouseleave";
    else
        return "mouseout";

}
function evt_ChangeLocationPSMouseOverOut(e) {
    var sourceElement = Event.element(e);
    var args = $A(arguments);

    var myId = args[1];
    var isOver = args[2];

    ChangeLocationPSMouseEvent(myId, isOver);
}
function ChangeLocationPSMouseEvent(elm, pid, isOver) {

    var selectedDivId = $(elm).attr('id');

    if (changeLocation_PredictiveSelectedId != null && $(changeLocation_PredictiveSelectedId) != null) {
        $(changeLocation_PredictiveSelectedId).addClass('HdrPop_PerdictiveRow_Prod');
    }

    if (isOver) {
        $(elm).attr('class', 'HdrPop_PerdictiveRow_Prod_hover');
        changeLocation_PredictiveSelectedId = selectedDivId;
    }
    else {
        $(elm).attr('class', 'HdrPop_PerdictiveRow_Prod');
        changeLocation_PredictiveSelectedId = null;
    }
}
function ChangeLocation_PSearchSelectDiv(inc) {
    var pLocationRow;

    if (navigator.appName == "Microsoft Internet Explorer") ///This only for IE
    {
        pLocationRow = $('.HdrPop_Perdictive_city'); //modified by Dipin Kumar, due to IE issues.
        for (var intCount = 0; intCount < pLocationRow.length; intCount++)
            pLocationRow[intCount] = pLocationRow[intCount].parentElement;
    }
    else
        pLocationRow = document.getElementsByName('pLocationRow');


    if (pLocationRow != null && pLocationRow.length > 0) {
        var pointer = -1;
        if (changeLocation_PredictiveSelectedId != null) {
            for (var i = 0; i < pLocationRow.length; i++) {

                if (changeLocation_PredictiveSelectedId == pLocationRow[i].id) {
                    pointer = i;
                    pLocationRow[i].className = 'HdrPop_PerdictiveRow_Prod';
                    break;
                }
            }
        }
        pointer = (pointer + inc);
        if (pointer < 0) pointer = pLocationRow.length - 1;
        if (pointer >= pLocationRow.length) pointer = 0;
        changeLocation_PredictiveSelectedId = pLocationRow[pointer].id;
        pLocationRow[pointer].className = 'HdrPop_PerdictiveRow_Prod_hover';

        if (pLocationRow[pointer].getAttribute('itemnum') >= 6) {
            if (inc == 1)
                $('#divChangeLocationPredictiveSearch').scrollTop((pLocationRow[pointer].getAttribute('itemnum') - 6) * 43);
            else {
                if (pLocationRow[pointer].getAttribute('itemnum') >= 6)
                    $('#divChangeLocationPredictiveSearch').scrollTop((pLocationRow[pointer].getAttribute('itemnum') - 6) * 43);
                else
                    $('#divChangeLocationPredictiveSearch').scrollTop($('divChangeLocationPredictiveSearch').scrollTop() - 43);
            }
        }
        else {
            $('#divChangeLocationPredictiveSearch').scrollTop(0);
        }
    }
}
function SearchPredictiveChangeLocation(event, txtbox, OnEnterPressedFunction, flag) {
    //include_css("http://" + getHostPath() + "/App_Themes/Main/PredSrhChgLoc/PredSrhChgLoc.css");
    event = event || window.event;
    if (psS_TimeOut_PSChangeLoc != null) clearTimeout(psS_TimeOut_PSChangeLoc); //clear the time out
    var code = (event.keyCode ? event.keyCode : event.which);
    //alert(code);
    switch (code) {
        case 13: //enter key pressed
            ChangeLocationPSMouseClick(OnEnterPressedFunction);
            break;
        case 27: // esc key pressed
            DeletePredictiveSearch_ChangeLocation();
            break;
        case 38: // up key pressed
            ChangeLocation_PSearchSelectDiv(-1);
            break;
        case 40: // down key pressed
            ChangeLocation_PSearchSelectDiv(1);
            break;
        default:
            //DeletePredictiveSearch_ChangeLocation();
            if (txtbox.value.length > 1) {
                psS_TimeOut_PSChangeLoc = setTimeout("LoadAndDisplaySearchPredictiveCities_ChangeLocation('" + txtbox.value + "', '" + txtbox.id + "', " + OnEnterPressedFunction + ",'" + flag + "')", 100);     //display the predictive search here.
            }
            else {
                DeletePredictiveSearch_ChangeLocation();
            }

    } //end switch
}
function bindTemplatesOnPredictiveSearch(keywords) {
    //alert("function to bind templates");
    var searchText = keywords;
    if (searchText != "Search" && searchText != null && searchText != "") {
        pageNO = 1;
        loadedPageNo = 1;
        var parentDiv = $('#themeContainerParent');
        var moduleName = "../../_modules/settings/ucThemeContainer.ascx";
        var _params = "&kword=" + searchText + "&Pno=" + pageNO + '&Psize=' + pageSize + '&Sort=' + 1 + '&Dir=' + 1 + '&dx=' + selectedItemIndex;
        var opts = { 'onsucess': function () {
            pageNO = pageNO + 1;
            $('#themeContainerParent').scrollTop(0);
        }, 'params': _params
        };
        loadModuler(moduleName, parentDiv, opts);
    }
    else {
        pageNO = 1;
        var parentDiv = $('#themeContainerParent');
        var moduleName = "../../_modules/settings/ucThemeContainer.ascx";
        var _params = "&kword=" + "&Pno=" + pageNO + '&Psize=' + pageSize + '&Sort=' + 1 + '&Dir=' + 1 + '&dx=' + selectedItemIndex + "&siteID=" + Sid;
        var opts = { 'onsucess': function () {
            pageNO = pageNO + 1;
            $('#themeContainerParent').scrollTop(0);
        }, 'params': _params
        };
        loadModuler(moduleName, parentDiv, opts);
    }
}